package maa.action.client;

import maa.action.Action;
import maa.action.ActionResult;
import maa.dao.h2.ClientDAOimpl;
import maa.dao.DAOCommand;
import maa.dao.DAOFactory;
import maa.dao.DAOManager;
import maa.database.ConnectionPool;
import maa.entity.User;
import maa.action.ActionException;
import maa.dao.DAOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class SubscribeForCourse implements Action {
    @Override
    public ActionResult execute(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        HttpSession session = req.getSession();
        ActionResult actionResult = new ActionResult();
        ConnectionPool connectionPool = ConnectionPool.getInstance();
        DAOManager daoManager = DAOFactory.createDAOManager(connectionPool.getConnection());
        String string = req.getParameter("course-uuid").substring(0, req.getParameter("course-uuid").length() - 1);
        final UUID uuid = UUID.fromString(string);
        final User user = (User) session.getAttribute("user");
        DAOCommand daoCommand = new DAOCommand() {
            @Override
            public Object execute(DAOManager daoManager) throws ActionException {
                ClientDAOimpl clientDAO = daoManager.getClientDAO();
                List<UUID> uuidList = new ArrayList<UUID>();
                try {
                    uuidList = clientDAO.findUserSubscriptions(user);
                } catch (DAOException e) {
                    throw new ActionException("Exception in clientDAO.findUserSubscriptions(user)&courseDAO.findCoursesById(uuidList)");
                }
                return uuidList;
            }
        };
        List<UUID> list = (List<UUID>) daoManager.executeAndClose(daoCommand);
        if(list.contains(uuid)) {
            req.setAttribute("already_subscribed","You have already subscribed to this course!");
            actionResult.setResult("courses");
            return actionResult;
        }
        daoManager.setConnection(connectionPool.getConnection());
        DAOCommand command = new DAOCommand() {
            @Override
            public Object execute(DAOManager daoManager) throws ActionException {
                try {
                    return daoManager.getClientDAO().addCourse(user, uuid);
                } catch (DAOException e) {
                    throw new ActionException("Exception in clientDAO.addCourse(user, uuid)");
                }
            }
        };
        Boolean flag = (Boolean) daoManager.executeAndClose(command);
        if (flag)
        {
            actionResult.setResult("courses");
            actionResult.setRedirected(true);
        }
        return actionResult;
    }
}
